define(['app'], function(app) {
    app.controller('ImportMockController', function($uibModalInstance, xContext, xUtil, toastr) {
        var self = this;
        self.type = '';
        self.module = '';
        self.parent = '';
        self.overwrite = true;
        self.file = null;

        self.init = function() {
            self.type = xContext.type;
            self.module = xContext.module;
            self.parent = xContext.node.parent;
            if (xContext.node.root) {
                self.parent = '/';
            } else if (!xContext.node.leaf) {
                self.parent = self.parent + '/' + (xContext.node.oldname || xContext.node.name);
            }
            if (!self.parent) {
                self.parent = '/';
            }
        }

        self.submit = function(valid) {
            if (valid) {
                var path = self.module + self.parent;
                var params = '?overwrite=' + self.overwrite;
                if (self.type == 'doc') {
                    path = path + (path.lastIndexOf('/') == 0 ? '' : '/') + self.file.name;
                    params = params + '&path=' + path;
                    xUtil.file.upload('/mock/data/import' + params, self.file).then(function(response) {
                        if (response.data) {
                            toastr.success('文件【' + self.file.name +'】已导入！');
                            $uibModalInstance.close(path);
                        }
                    });
                } else if (self.type == 'zip') {
                    params = params + '&path=' + path;
                    xUtil.file.upload('/mock/data/bulk-import' + params, self.file, 'PUT').then(function(response) {
                        if (response.data) {
                            toastr.success('压缩包【' + self.file.name +'】已导入！');
                            $uibModalInstance.close(path);
                        }
                    });
                }
            }
        }

        self.upload = function(file) {
            if (file) {
                self.file = file;
            }
        }

        self.cancel = function() {
            $uibModalInstance.dismiss();
        }
    });
});
